package cn.org.timespace.ons.inside.mina.filter.command;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;

import cn.org.timespace.ons.inside.mina.filter.ESInProtocalPack;
import cn.org.timespace.ons.util.AryUtil;

public abstract class AbstractESInCommand implements ESInCommand {

	private final static Log log = LogFactory.getLog(AbstractESInCommand.class);
	
	@Override
	public abstract void processPackage(IoSession session, ESInProtocalPack pack);

	@Override
	public boolean checkPackage(ESInProtocalPack pack) {
		return checkPackage(pack, ESInProtocalPack.SYNC_FRAME_NAME_UP);
	}
	
	public boolean checkPackage(ESInProtocalPack pack, String syncFrameName) {
		if(!checkSyncFrame(pack.getSyncFrame(), syncFrameName)) {
			log.error(pack.toString());
			return false;
		}
		
		if(!checkCode(pack.getFunctionNo(), pack.getPackageContents(), pack.getCheckCode())) {
			log.error(pack.toString());
			return false;
		}
		
		return true;
	}
	
	/**
	 * 检查同步帧
	 * @param syncFrame
	 * @param syncFrameName:指定同步帧(ZJX或JXT)
	 * @return
	 */
	private boolean checkSyncFrame(String syncFrame, String syncFrameName) {
		boolean result = true;
		
		if(!syncFrame.equalsIgnoreCase(syncFrameName)) {
			log.error("同步帧非" + syncFrameName + ",丢弃包");
			result = false;
		}
		return result;
	}
	
	/**
	 * 检查校验和
	 * @param pack
	 * @return
	 */
	private boolean checkCode(String functionNo, String packageContents, String checkCode) {
		boolean result = true;
		
		String contentsIntHex = AryUtil.string2HexAdd(functionNo + packageContents);//内容部分(功能号+包内容）计算校验和
		String code = contentsIntHex.substring(contentsIntHex.length() - 2, contentsIntHex.length());//取最后两位
		
		if(!code.equalsIgnoreCase(checkCode)) {
			log.error("校验和验证错误！丢弃包");
			result = false;
		}
		
		return result;
	}
	
}
